// pages/my/info.js
var app = getApp()
import { BASE_URL } from '../../api/index'
import {
  editUserInfo
} from '../../api/user.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    qrcode: '',
    isShowBox: false,
    base64: '',
    isShowEditName: false,
    sendBtnTxt: '发送验证码',
    sending: false,
    array: [
      '男', '女'
    ],
    index: 0,
    sex: ''
  },
  showSexBox() {
    this.setData({
      showSex: true
    })
  },
  bindPickerChange: function (e) {
    console.log(e)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      sex: this.data.array[e.detail.value]
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(app.globalData.user)
    let that = this
    that.setData({
      user: app.globalData.userInfo,
      sex: app.globalData.userInfo.sex == 1 ? '男' : '女',
    })
  },
  test() {
    wx.requestPayment({
      timeStamp: "1659080575",
      nonceStr: "1659080575451",
      package: "prepay_id=wx291542554308903a153ad2ee1f87490000",
      signType: "RSA",
      paySign: "IoFKgTteuUO0U9zG5y6UZCjiZpFZNky19oLjx7QGRBKdnAH3+dOo8jFKpVt/cEcixr4cLMgJA95BMS2W10Kf8wKbOqq++OYM2IdRCv31/v1XkeGYmvZp+eEpO0G+6QwEKg2vyEfsxWUexc6uixDoYxKl2MI+hfC6xC4MHD35+T8J1t0YDK8naBB4trGPy1poUBQj+u/HnnNoPhq5dA1XNTn/aNVTTsiQ4ghsz3A4Ir6b4pcdEbG5/iSjzw4mo537pDuWIb43TovXiiAXgsls66s4XQypxDU2w1lDc8u0OX9II/yUvv09n0wEtNZGRXBV4dr5IwUxi5HG+ZaCKUTqeA==",
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1 //返回上一级页面
              })
            }, 1500)
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '已取消支付',
          icon: 'success',
          duration: 1500,
          // success: () => {
          //   setTimeout(function () {
          //     wx.navigateBack({
          //       delta: 1 //返回上一级页面
          //     })
          //   }, 1500)
          // }
        })
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },
  async changeImg() {
    let that = this
    wx.chooseMedia({
      count: 1, // 默认9
      mediaType: ['image'],
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '上传中...',
          mask: true
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFiles[0].tempFilePath
        console.log(tempFilePaths)
        // console.log(tempFilePaths + '----');
        wx.uploadFile({
          url: BASE_URL + 'system/common/file/upload', //接受图片的接口地址
          filePath: tempFilePaths,
          name: 'file',
          success(res) {
            let resp = JSON.parse(res.data)
            //do something
            that.data.user.face = resp.data
            that.setData({
              user: that.data.user
            })
            wx.hideLoading()
          },
          complete(){
            wx.hideLoading()
          }
        })
      }
    })
  },
  async saveName() {
    if (!this.data.name) {
      wx.showToast({
        title: '请输入您的姓名',
        icon: 'none'
      })
      return
    }
    this.data.user.nickName = this.data.name
    this.setData({
      user: this.data.user,
      isShowEditName: false
    })
    // app.postForm('user/update_user_info_nickname_by_id',{NickName:this.data.name,Id:app.globalData.uid},res=>{
    //   wx.hideLoading({
    //     success: (res) => {},
    //   })
    //   if(res&&res.code=='0'){        
    //     let user=this.data.user;
    //     user.NickName=this.data.name;
    //     app.globalData.user.NickName=this.data.name;
    //     var pages = getCurrentPages();
    //     var prevPage = pages[pages.length - 2];  //上一个页面
    //     prevPage.setData({
    //       nickName:this.data.name
    //     })
    //     this.setData({
    //       user:user,
    //       isShowEditName:false
    //     })
    //   }else{
    //     wx.showToast({
    //       title: res.msg,
    //       icon:'none'
    //     })
    //   }
    // })
  },
  inputName(e) {
    console.log(e)
    this.setData({
      name: e.detail.value
    })
  },
  bindName() {
    this.setData({
      isShowEditName: true
    })
  },
  bindTel(e) {
    this.setData({
      isShowBindTel: true
    })
  },
  inputTel(e) {
    this.setData({
      tel: e.detail.value
    })
  },
  inputCode(e) {
    this.setData({
      code: e.detail.value
    })
  },
  send(e) {

    if (this.data.sending) {
      return
    }
    this.setData({
      rcode: Math.ceil(Math.random() * 100000)
    })
    if (!this.data.tel) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'error'
      })
      return
    }

    let count = 60;
    this.setData({
      sending: true
    })
    let index = setInterval(() => {
      if (count == 0) {
        this.setData({
          sendBtnTxt: '发送验证码',
          sending: false,
        })
        clearInterval(index);
        return;
      }
      count = count - 1;
      this.setData({
        sendBtnTxt: `(${count})后重新发送`
      })
    }, 1000)

  },
  async save() {
    wx.showLoading({
      title: '加载中...',
    })
    let sex = this.data.sex == '男' ? 1 : 0
    this.data.user.sex = sex
    let res = await editUserInfo(wx.getStorageSync('access_token'), this.data.user.nickName, this.data.user.face, sex)
    if (res && res.code == 10000) {
      app.globalData.userInfo = this.data.user
      wx.hideLoading()
      wx.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(function () {
            wx.navigateBack({
              delta: 1 //返回上一级页面
            })
          }, 1500)
        }
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },
  close(e) {
    this.setData({
      isShowEditName: false,
      isShowBindTel: false,
    })
  },
  download() {
    const that = this;
    var filepath = wx.env.USER_DATA_PATH + '/test.png';
    //获取文件管理器对象
    var aa = wx.getFileSystemManager();
    aa.writeFile({
      filePath: filepath,
      data: that.data.base64,
      encoding: 'base64',
      success: res => {
        wx.showLoading({
          title: '正在保存...',
          mask: true
        });
        //保存图片到相册
        wx.saveImageToPhotosAlbum({
          filePath: filepath,
          success: function (res) {
            wx.hideLoading();
            wx.showToast({
              title: '保存成功！',
              icon: 'success',
              duration: 2000 //持续的时间
            })
          },
          fail: function (err) {
            wx.hideLoading();
            if (errerrMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击下载按钮进行保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  genQrcode() {
    var that = this;
    wx.showLoading({
      title: '生成中...',
      mask: true
    })
    wx.request({
      url: `https://wxapp-dl.51xk.info/api/MiniApp/get_qrcode?id=${app.globalData.uid}`,
      success(res) {
        if (res.statusCode == 200) {
          let url = `data:image/jpeg;base64,${res.data}`
          that.setData({
            qrcode: url,
            base64: res.data,
            isShowBox: true
          })
        }
      },
      fail(res) {
        wx.showModal({
          content: res
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  // genSharePic() {
  //   if (!this.data.user) {
  //     wx.showToast({
  //       title: '您还不是经销商',
  //       icon: 'none'
  //     });
  //     return
  //   }
  //   wx.showLoading({
  //     title: '制作中',
  //     mask: true,
  //   })
  //   var param = {
  //     CustId: app.globalData.uid,
  //     CustName: this.data.user.NickName,
  //     HeadImg: this.data.user.HeadImg
  //   }
  //   app.postForm("/qiniu/q/upload_sharepic.php", param, res => {
  //     console.log(res);
  //     wx.hideLoading({
  //       success: (res) => {},
  //     })
  //     if (res && res.code == "0") {
  //       this.setData({
  //         sharePic: res.file
  //       })
  //       app.postForm(`user/update_user_info_sharepic_by_id`, {
  //         SharePic: res.file,
  //         Id: app.globalData.uid
  //       })
  //       wx.showToast({
  //         title: '生成成功',
  //       })
  //     } else {
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'error'
  //       })
  //     }
  //   })
  // },
  goBack() {
    wx.navigateTo({
      url: '/pages/my/gotBack',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})